<script setup lang="ts">
import { ref, computed, watch, onMounted, defineAsyncComponent } from 'vue';
import { useRoute } from 'vue-router';
import { useAppStore } from '@/store';
import { useThemeStore } from '@/store/modules/theme';
import { ElCard, ElAvatar, ElDescriptions, ElDescriptionsItem, ElTag, ElDivider, ElButton, ElMessage, ElDialog, ElSkeleton, ElSkeletonItem } from 'element-plus';
import { Edit, Plus } from '@element-plus/icons-vue';
import { $t } from '@/locales';
import { userGenderRecord, enableStatusRecord } from '@/constants/business';
import { useAuthStore } from '@/store/modules/auth';
import { fetchGetUserById } from '@/service/api/system-manage';

// Try to import the MaterialImage component, but handle failure gracefully
let MaterialImage: any = null;
try {
  // Dynamic import to avoid TypeScript errors
  MaterialImage = defineAsyncComponent(() => import('@/views/function/material/Image/index.vue'));
} catch (error) {
  console.error('Failed to load MaterialImage component:', error);
}

// Flag to track if the material component is available
const isMaterialComponentAvailable = computed(() => MaterialImage !== null);

const route = useRoute();
const appStore = useAppStore();
const themeStore = useThemeStore();
const authStore = useAuthStore();

// Loading state
const loading = ref(false);

// Get user info from auth store initially
const userInfo = computed(() => authStore.userInfo);

// For avatar upload
const avatarUrl = computed(() => userInfo.value.userImages || 'http://127.0.0.1:9000/image-bucket/20250514/fbee6c07a7d24746884456b56b6a21bfd1ee7e8c-5af4-462a-bf59-e58a053dba21.jpg');

// Material uploader dialog
const showMaterialUploader = ref(false);
const selectedImage = ref('');

// Handle selecting an image from the material component
const selectMaterialImage = (url: string) => {
  if (url) {
    selectedImage.value = url;
    // Update user avatar immediately
    updateUserAvatar(url);
    showMaterialUploader.value = false;
  }
};

// Update user avatar in the auth store
const updateUserAvatar = (url: string) => {
  if (url) {
    authStore.updateUserAvatar(url);
    ElMessage.success($t('page.userCenter.avatarUploadSuccess'));
  }
};

// Load user details from API
const loadUserDetails = async () => {
  try {
    loading.value = true;
    
    // Get userId from route query or auth store
    const queryUserId = route.query.userId;
    const userId = queryUserId || userInfo.value.userId;
    
    if (!userId) {
      ElMessage.error('用户ID不存在，无法加载用户信息');
      return;
    }
    
    console.log('Loading user details for userId:', userId);
    
    // Call API to get user details
    const { data, error } = await fetchGetUserById(Number(userId));
    
    if (error || !data) {
      console.error('Failed to load user details:', error);
      ElMessage.error('加载用户信息失败');
      return;
    }
    
    // Update auth store with user details
    await authStore.fetchUserDetails(Number(userId));
    
  } catch (err) {
    console.error('Error loading user details:', err);
    ElMessage.error('加载用户信息失败');
  } finally {
    loading.value = false;
  }
};

// Load user details when component is mounted
onMounted(() => {
  loadUserDetails();
});

// User stats based on user info
const userStats = computed(() => [
  { 
    label: $t('page.userCenter.loginCount'), 
    value: userInfo.value.loginCount || '0'
  },
  { 
    label: $t('page.userCenter.lastLogin'), 
    value: userInfo.value.lastLoginTime ? new Date(userInfo.value.lastLoginTime).toLocaleString() : '未登录'
  },
  { 
    label: $t('page.userCenter.registerDate'), 
    value: userInfo.value.createTime ? new Date(userInfo.value.createTime).toLocaleDateString() : '未知'
  },
]);

// Example recent activities - can be fetched from backend if available
const recentActivities = [
  { date: '2024-05-14', action: $t('page.userCenter.activity.login'), time: '15:30' },
  { date: '2024-05-13', action: $t('page.userCenter.activity.updateProfile'), time: '09:45' },
  { date: '2024-05-10', action: $t('page.userCenter.activity.changePassword'), time: '11:20' },
];
</script>

<template>
  <div class="user-center-container p-20px">
    <div v-if="loading" class="loading-container">
      <ElSkeleton :rows="10" animated />
    </div>
    
    <div v-else class="user-center-content">
      <div class="user-center-header flex gap-24px flex-wrap">
        <!-- User Avatar and Basic Info Card -->
        <ElCard class="flex-1 min-w-300px" :body-style="{ padding: '20px' }">
          <div class="flex items-start gap-20px flex-wrap md:flex-nowrap">
            <div class="avatar-container relative">
              <ElAvatar :size="100" :src="avatarUrl" />
              <div class="avatar-upload">
                <ElButton 
                  type="primary" 
                  circle 
                  size="small" 
                  class="upload-button" 
                  :icon="Edit" 
                  @click="showMaterialUploader = true"
                  v-if="isMaterialComponentAvailable"
                />
              </div>
            </div>
            <div class="user-info flex-1">
              <h2 class="text-xl font-semibold mb-8px">{{ userInfo.userName || 'Admin User' }}</h2>
              <p class="text-gray opacity-80 mb-12px">{{ userInfo.nickName || 'System Administrator' }}</p>
              
              <div class="flex flex-wrap gap-8px mt-16px">
                <ElTag 
                  v-for="role in userInfo.roles" 
                  :key="role" 
                  :type="themeStore.themeColor.primary"
                  effect="light"
                >
                  {{ role }}
                </ElTag>
              </div>
              
              <div class="user-stats flex gap-16px mt-16px">
                <div v-for="(stat, index) in userStats" :key="index" class="stat-item text-center">
                  <div class="stat-value font-semibold">{{ stat.value }}</div>
                  <div class="stat-label text-xs opacity-70">{{ stat.label }}</div>
                </div>
              </div>
            </div>
          </div>
        </ElCard>

        <!-- User Details Card -->
        <ElCard class="flex-1 min-w-300px mt-0 md:mt-0" :body-style="{ padding: '20px' }">
          <template #header>
            <div class="flex justify-between items-center">
              <h3 class="m-0">{{ $t('page.userCenter.contactInfo') }}</h3>
              <ElButton type="primary" plain size="small" :icon="Edit">
                {{ $t('common.edit') }}
              </ElButton>
            </div>
          </template>
          
          <ElDescriptions :column="1" border>
            <ElDescriptionsItem :label="$t('page.manage.user.userPhone')">
              {{ userInfo.userPhone || '未设置' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('page.manage.user.userEmail')">
              {{ userInfo.userEmail || '未设置' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('page.manage.user.userGender')">
              <ElTag v-if="userInfo.userGender" type="primary">
                {{ $t(userGenderRecord[userInfo.userGender]) }}
              </ElTag>
              <span v-else>未设置</span>
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="$t('page.manage.user.userStatus')">
              <ElTag v-if="userInfo.status" :type="String(userInfo.status) === '1' ? 'success' : 'warning'">
                {{ $t(enableStatusRecord[String(userInfo.status)]) }}
              </ElTag>
              <span v-else>未设置</span>
            </ElDescriptionsItem>
          </ElDescriptions>
        </ElCard>
      </div>

      <!-- Recent Activity Card -->
      <ElCard class="mt-24px">
        <template #header>
          <div class="card-header">
            <h3 class="m-0">{{ $t('page.userCenter.recentActivity') }}</h3>
          </div>
        </template>
        
        <div class="timeline">
          <div v-for="(activity, index) in recentActivities" :key="index" class="timeline-item">
            <div class="timeline-dot" :style="{ 'background-color': themeStore.themeColor.primary }"></div>
            <div class="timeline-content">
              <div class="flex justify-between">
                <div class="activity-action">{{ activity.action }}</div>
                <div class="activity-time text-sm opacity-60">{{ activity.time }}</div>
              </div>
              <div class="activity-date text-sm opacity-70">{{ activity.date }}</div>
            </div>
          </div>
        </div>
      </ElCard>
      
      <!-- Material Image Upload Dialog -->
      <ElDialog v-if="isMaterialComponentAvailable" v-model="showMaterialUploader" title="选择头像" width="800px" destroy-on-close>
        <component :is="MaterialImage" flag="1" @selectImage="selectMaterialImage" />
      </ElDialog>
    </div>
  </div>
</template>

<style scoped lang="scss">
.user-center-container {
  max-width: 1200px;
  margin: 0 auto;
}

.loading-container {
  padding: 20px;
}

.avatar-container {
  position: relative;
  display: inline-block;
}

.avatar-upload {
  position: absolute;
  right: 0;
  bottom: 0;
}

.upload-button {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.timeline {
  position: relative;
  padding-left: 20px;
}

.timeline-item {
  position: relative;
  padding-bottom: 20px;
  padding-left: 20px;
}

.timeline-item:last-child {
  padding-bottom: 0;
}

.timeline-dot {
  position: absolute;
  left: -5px;
  top: 5px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: v-bind('themeStore.themeColor.primary');
}

.timeline-item:not(:last-child)::before {
  content: '';
  position: absolute;
  left: 0;
  top: 15px;
  height: calc(100% - 15px);
  width: 1px;
  background-color: #e0e0e0;
}

.activity-date {
  margin-top: 4px;
}

/* Dark mode adjustments */
:deep(.dark .timeline-item:not(:last-child)::before) {
  background-color: #4a4a4a;
}
</style>
